package io.wdb.modules.generator.generator.controller.updown;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import io.wdb.common.utils.DateFormatUtil;
import io.wdb.common.utils.DateUtils;
import io.wdb.common.utils.LeadExportUtil;
import io.wdb.common.utils.PoiStyle;
import io.wdb.common.utils.Query;
import io.wdb.modules.generator.generator.controller.api.BaseController;
import io.wdb.modules.generator.generator.entity.customer.BookInfoEntityCustomer;
import io.wdb.modules.generator.generator.entity.customer.BookInfoExport;
import io.wdb.modules.generator.generator.entity.customer.UserInfoEntityCustomer;
import io.wdb.modules.generator.generator.entity.web.BaseResponse;
import io.wdb.modules.generator.generator.entity.web.ResponseEnum;
import io.wdb.modules.generator.generator.entity.web.WebResponse;
import io.wdb.modules.generator.generator.service.BookBatchImportService;
import io.wdb.modules.generator.generator.service.UpDownLoadFileService;
import io.wdb.modules.generator.generator.service.client.ClientManagerService;

@RestController
@RequestMapping("upDown/file")
@Scope(value="prototype")
public class UpDownLoadFileController extends BaseController{
	
	private Logger logger = LoggerFactory.getLogger(UpDownLoadFileController.class);
	@Autowired
	private PoiStyle poiStyle;
	
	@Autowired
	private UpDownLoadFileService upDownLoadFileService;
	
	@Autowired
	private BookBatchImportService bookBatchImportService;
	
	@Autowired
	private ClientManagerService clientManagerService;
	
	@Value("${wdb007.upload.path}")
	private String uploadPath; 
	
	@RequestMapping("upexecel")
	public BaseResponse uploadExcel(HttpServletRequest request){
		BaseResponse baseResponse = success();
		try {
			WebResponse response = new WebResponse();
			List<MultipartFile> multipartFiles = ((MultipartHttpServletRequest) request).getFiles("file");
			if (multipartFiles == null || multipartFiles.size() < 1) {
				logger.info("用户未上传文件");
				response.setCode(ResponseEnum.NO_UPLOAD_EXCEL.getCode());
				response.setMessage(ResponseEnum.NO_UPLOAD_EXCEL.getMessage());
				baseResponse.setDetail(response);
				return baseResponse;
				//未上传图片，不做处理
			} else {
				for(MultipartFile multipartFile:multipartFiles) {
					response = upDownLoadFileService.analysisExcel(multipartFile);
					if(response!=null) {
						baseResponse.setDetail(response);
						return baseResponse;
					}
				}
			}
		} catch (Exception e) {
			baseResponse = failed(e);
			logger.error(e.getMessage(),e);
		}
		return baseResponse;
	}
	/**
	 * 
	 * @Method:exportUserPrize
	 * @Description:导出文件
	 * @Time 2018年1月25日 下午7:41:57
	 * @author: Tom
	 * @param request
	 * @param response
	 * @param ids
	 * @param user_id
	 */
	@RequestMapping("/export")
	public void exportUserPrize(HttpServletRequest request, HttpServletResponse response) {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			String dateStr = DateUtils.format(new Date());
			String paramToken = request.getParameter("currentTime");
			String currentTime = paramToken.split("-")[1];
			Map<String,Object> params = new HashMap<String,Object>();
			params.put("currentTime", currentTime);
			List<BookInfoEntityCustomer> bookInfoEntityCustomers = bookBatchImportService.list(params);
			List<BookInfoExport> bookInfoExports = new ArrayList<BookInfoExport>();
			for(BookInfoEntityCustomer bookInfoEntityCustomer:bookInfoEntityCustomers) {
				BookInfoExport bookInfoExport = new BookInfoExport();
				BeanUtils.copyProperties(bookInfoEntityCustomer, bookInfoExport);
				bookInfoExports.add(bookInfoExport);
			}
			BookInfoExport bookInfoExportErrorTag = new BookInfoExport();
			bookInfoExportErrorTag.setIsbnNo("-");
			bookInfoExports.add(bookInfoExportErrorTag);
			BufferedReader bufferedReader = new BufferedReader(new FileReader(new File(uploadPath+dateStr+"/"+paramToken.substring(0, paramToken.indexOf("."))+".txt")));
			String readLine = null;
			while((readLine=bufferedReader.readLine())!=null){
				String[] strs = readLine.split("\\|");
				BookInfoExport bookInfoExport = new BookInfoExport();
				bookInfoExport.setIsbnNo(strs[0]);
				bookInfoExport.setBookName(strs[1]);
				bookInfoExport.setAuthor(strs[2]);
				bookInfoExport.setReadAge(strs[3]);
				bookInfoExport.setCategory(strs[5]);
				bookInfoExport.setPress(strs[6]);
				bookInfoExport.setPublicationDate(DateFormatUtil.parseDatePattern(strs[7], DateFormatUtil.DATE_PATTERN_LEAN));
				bookInfoExport.setPrice(new BigDecimal(strs[8]));
				bookInfoExport.setBrief(strs[9]);
				bookInfoExport.setDescribe(strs[10]);
				bookInfoExport.setRecommendationer(strs[11]);
				bookInfoExport.setRecommendation(strs[12]);
				bookInfoExports.add(bookInfoExport);
			}
			String fileName = "export-prize";
			//先生成要导出的xls文件，并返回文件存储目录
			String filePath = LeadExportUtil.intoServerXls(bookInfoExports,fileName);
			//下面是读取生成的文件并进行下载操作
			response.setContentType("application/x-msdownload");  
            response.setCharacterEncoding("utf-8");  
            response.setHeader("Content-disposition", "attachment;filename="+fileName+DateFormatUtil.formatDateTime(new Date())+".xls");  
            // 通知客户文件的MIME类型：  
            bis = new BufferedInputStream(new FileInputStream((filePath)));
            bos = new BufferedOutputStream(response.getOutputStream()); 
            byte[] buff = new byte[2048];  
            int bytesRead;
            int i = 0;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
                bos.write(buff, 0, bytesRead);  
                i++;  
            }
            bos.flush();
            logger.info("文件导出成功"+fileName);
		}catch (Exception e) {
			logger.info(e.getMessage(),e);
		}finally {  
            if (bis != null) {  
                try {  
                    bis.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
                bis = null;  
            }  
            if (bos != null) {  
                try {  
                    bos.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
                bos = null;  
            }  
        } 
	}
	/**
	 * 
	 * @Method:exportUserManager
	 * @Description:导出客户管理中的客户数据
	 * @Time 2018年1月25日 下午7:41:57
	 * @author: Tom
	 * @param request
	 * @param response
	 * @param ids
	 * @param user_id
	 */
	@RequestMapping("/export-user-capital")
	public void exportUserManager(HttpServletRequest request, HttpServletResponse response) {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			Query query = new Query();
			List<UserInfoEntityCustomer> userInfoEntityCustomers = clientManagerService.queryList(query);
			
			HSSFWorkbook workbook = new HSSFWorkbook();
			HSSFSheet sheet = workbook.createSheet("客户资金信息");
			HSSFRow rowHead = sheet.createRow(0);
			//各个表头数据
			Cell cellHeadUserName = rowHead.createCell(0);
			cellHeadUserName.setCellValue("用户名");
			//cellHeadUserName.getCellStyle().cloneStyleFrom(poiStyle.headStyle(workbook));
			cellHeadUserName.setCellStyle(poiStyle.headStyle(workbook));
			
			Cell cellHeadPhone = rowHead.createCell(1);
			cellHeadPhone.setCellValue("手机号");
			//cellHeadPhone.getCellStyle().cloneStyleFrom(poiStyle.headStyle(workbook));
			cellHeadPhone.setCellStyle(poiStyle.headStyle(workbook));
			
			Cell cellHeadDeposit = rowHead.createCell(2);
			cellHeadDeposit.setCellValue("押金");
			//cellHeadDeposit.getCellStyle().cloneStyleFrom(poiStyle.headStyle(workbook));
			cellHeadDeposit.setCellStyle(poiStyle.headStyle(workbook));
			
			
			Cell cellHeadCash = rowHead.createCell(3);
			cellHeadCash.setCellValue("账户余额");
			//cellHeadCash.getCellStyle().cloneStyleFrom(poiStyle.headStyle(workbook));
			cellHeadCash.setCellStyle(poiStyle.headStyle(workbook));
			
			
			Cell cellHeadShelfCode = rowHead.createCell(4);
			cellHeadShelfCode.setCellValue("书柜号");
			//cellHeadShelfCode.getCellStyle().cloneStyleFrom(poiStyle.headStyle(workbook));
			cellHeadShelfCode.setCellStyle(poiStyle.headStyle(workbook));
			
			Cell cellHeadBorrowed = rowHead.createCell(5);
			cellHeadBorrowed.setCellValue("借阅图书数量");
			//cellHeadBorrowed.getCellStyle().cloneStyleFrom(poiStyle.headStyle(workbook));
			cellHeadBorrowed.setCellStyle(poiStyle.headStyle(workbook));
			
			Cell cellHeadBorrowCurrent = rowHead.createCell(6);
			cellHeadBorrowCurrent.setCellValue("在借图书数量");
			//cellHeadBorrowCurrent.getCellStyle().cloneStyleFrom(poiStyle.headStyle(workbook));
			cellHeadBorrowCurrent.setCellStyle(poiStyle.headStyle(workbook));
			
			Cell cellHeadIntegral  = rowHead.createCell(7);
			cellHeadIntegral.setCellValue("积分");
			//cellHeadIntegral.getCellStyle().cloneStyleFrom(poiStyle.headStyle(workbook));
			cellHeadIntegral.setCellStyle(poiStyle.headStyle(workbook));
			
			Cell cellHeadCredit = rowHead.createCell(8);
			cellHeadCredit.setCellValue("信用分");
			//cellHeadCredit.getCellStyle().cloneStyleFrom(poiStyle.headStyle(workbook));
			cellHeadCredit.setCellStyle(poiStyle.headStyle(workbook));
			
			Cell cellHeadCreateTime = rowHead.createCell(9);
			cellHeadCreateTime.setCellValue("注册时间");
			//cellHeadCreateTime.getCellStyle().cloneStyleFrom(poiStyle.headStyle(workbook));
			cellHeadCreateTime.setCellStyle(poiStyle.headStyle(workbook));
			String fileName = "user-manager";
			//先生成要导出的xls文件，并返回文件存储目录
			this.intoServerXlsContent(workbook,sheet,userInfoEntityCustomers,fileName);
			for(int i=0;i<9;i++) {
				sheet.autoSizeColumn((short)i);
			}
			String filePath = null;
			FileOutputStream fos= null;
			try {
				fos = new FileOutputStream(fileName+DateFormatUtil.formatDate(new Date())+".xls");
				workbook.write(fos);
				fos.flush();
				filePath = fileName+DateFormatUtil.formatDate(new Date())+".xls";
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if(fos!=null) {
						fos.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			//下面是读取生成的文件并进行下载操作
			response.setContentType("application/x-msdownload");  
            response.setCharacterEncoding("utf-8");  
            response.setHeader("Content-disposition", "attachment;filename="+fileName+DateFormatUtil.formatDateTime(new Date())+".xls");  
            // 通知客户文件的MIME类型：  
            bis = new BufferedInputStream(new FileInputStream((filePath)));
            bos = new BufferedOutputStream(response.getOutputStream()); 
            byte[] buff = new byte[2048];  
            int bytesRead;
            int i = 0;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
                bos.write(buff, 0, bytesRead);  
                i++;  
            }
            bos.flush();
            logger.info("文件导出成功"+fileName);
		}catch (Exception e) {
			logger.info(e.getMessage(),e);
		}finally {  
            if (bis != null) {  
                try {  
                    bis.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
                bis = null;  
            }  
            if (bos != null) {  
                try {  
                    bos.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
                bos = null;  
            }  
        } 
	}
	/**
	 * 
	 * @Method:intoServerXlsContent
	 * @Description:导出用户记录
	 * @Time 2018年2月2日 下午4:35:56
	 * @author: Tom
	 * @param workbook 
	 * @param sheet
	 * @param userInfoEntityCustomers
	 * @param fileName
	 * @return
	 */
	private String intoServerXlsContent(HSSFWorkbook workbook, HSSFSheet sheet, List<UserInfoEntityCustomer> userInfoEntityCustomers,
			String fileName) {
		
		for(int i=1;i<userInfoEntityCustomers.size();i++) {
			Row row = sheet.createRow(i);
			sheet.autoSizeColumn(i-1, true);
			Cell cellUserName = row.createCell(0);
			cellUserName.setCellValue(userInfoEntityCustomers.get(i).getUserName());
			cellUserName.getCellStyle().cloneStyleFrom(poiStyle.normalBodyStyle(workbook));
			//cellUserName.setCellStyle(poiStyle.normalBodyStyle(workbook));
			
			Cell cellPhone = row.createCell(1);
			cellPhone.setCellValue(userInfoEntityCustomers.get(i).getMobileNo());
			cellPhone.getCellStyle().cloneStyleFrom(poiStyle.normalBodyStyle(workbook));
			//cellPhone.setCellStyle(poiStyle.normalBodyStyle(workbook));
			
			Cell cellDeposit = row.createCell(2);
			cellDeposit.setCellValue(userInfoEntityCustomers.get(i).getDepositAmount()==null?"":userInfoEntityCustomers.get(i).getDepositAmount().toString());
			cellDeposit.getCellStyle().cloneStyleFrom(poiStyle.normalBodyStyle(workbook));
			//cellDeposit.setCellStyle(poiStyle.normalBodyStyle(workbook));
			
			Cell cellCash = row.createCell(3);
			cellCash.setCellValue(userInfoEntityCustomers.get(i).getCashAmount()==null?"":userInfoEntityCustomers.get(i).getCashAmount().toString());
			cellCash.getCellStyle().cloneStyleFrom(poiStyle.normalBodyStyle(workbook));
			//cellCash.setCellStyle(poiStyle.normalBodyStyle(workbook));
			
			Cell cellShelfCode = row.createCell(4);
			cellShelfCode.setCellValue(userInfoEntityCustomers.get(i).getShelfCode()==null?"":userInfoEntityCustomers.get(i).getShelfCode());
			cellShelfCode.getCellStyle().cloneStyleFrom(poiStyle.normalBodyStyle(workbook));
			//cellShelfCode.setCellStyle(poiStyle.normalBodyStyle(workbook));
			
			Cell cellBorrowed = row.createCell(5);
			cellBorrowed.setCellValue(userInfoEntityCustomers.get(i).getBookCount()==null?0:userInfoEntityCustomers.get(i).getBookCount());
			cellBorrowed.getCellStyle().cloneStyleFrom(poiStyle.normalBodyStyle(workbook));
			//cellBorrowed.setCellStyle(poiStyle.normalBodyStyle(workbook));
			
			Cell cellBorrowCurrent = row.createCell(6);
			cellBorrowCurrent.setCellValue(userInfoEntityCustomers.get(i).getBorrowCount()==null?0:userInfoEntityCustomers.get(i).getBorrowCount());
			cellBorrowCurrent.getCellStyle().cloneStyleFrom(poiStyle.normalBodyStyle(workbook));
			//cellBorrowCurrent.setCellStyle(poiStyle.normalBodyStyle(workbook));
			
			Cell cellIntegral  = row.createCell(7);
			cellIntegral.setCellValue(userInfoEntityCustomers.get(i).getPointValue()==null?0:userInfoEntityCustomers.get(i).getPointValue());
			cellIntegral.getCellStyle().cloneStyleFrom(poiStyle.normalBodyStyle(workbook));
			//cellIntegral.setCellStyle(poiStyle.normalBodyStyle(workbook));
			
			Cell cellCredit = row.createCell(8);
			cellCredit.setCellValue(userInfoEntityCustomers.get(i).getCreditValue()==null?0:userInfoEntityCustomers.get(i).getCreditValue());
			cellCredit.getCellStyle().cloneStyleFrom(poiStyle.normalBodyStyle(workbook));
			//cellCredit.setCellStyle(poiStyle.normalBodyStyle(workbook));
			
			Cell cellCreateTime = row.createCell(9);
			String time = DateFormatUtil.formatDate(userInfoEntityCustomers.get(i).getCreateTime(),DateFormatUtil.DATETIME_PATTERN);
			cellCreateTime.setCellValue(time);
			cellCreateTime.getCellStyle().cloneStyleFrom(poiStyle.normalBodyStyle(workbook));
			//cellCreateTime.setCellStyle(poiStyle.timeStyle(workbook));
		}
		
		return null;
	}
}
